#!C:\python25\python.exe
# -*- coding: UTF-8 -*-

import  wx
import  wx.grid as gridlib

#---------------------------------------------------------------------------

class CustomDataTable(gridlib.PyGridTableBase):
    def __init__(self, log):
        gridlib.PyGridTableBase.__init__(self)
        self.log = log

        self.dicColLables = {
            1  : u'区 域',
            2  : u'变量名',
            3  : u'类 型',
            4  : u'长 度',
            5  : u'小数位',
            6  : u'格 式',
            7  : u'调整方式',
            8  : u'分 组?',
            9  : u'输 出?',
            10 : u'中文描述'
        }
        self.colLabels = self.dicColLables.values()

        self.dataTypes = [gridlib.GRID_VALUE_CHOICE + ': HEAD, DETAIL, TAIL',
                          gridlib.GRID_VALUE_STRING,
                          gridlib.GRID_VALUE_CHOICE + ': C, N, D',
                          gridlib.GRID_VALUE_NUMBER,
                          gridlib.GRID_VALUE_NUMBER,
                          gridlib.GRID_VALUE_CHOICE + ': all,MSW,GTK,other, ',
                          gridlib.GRID_VALUE_CHOICE + ': LERT, CENTER, RIGHT',
                          gridlib.GRID_VALUE_BOOL,
                          gridlib.GRID_VALUE_BOOL,
                          gridlib.GRID_VALUE_STRING
                          ]

        self.data = [
            [' HEAD',   'BANK_NAME', ' C', 40, 0, ' ',    ' LERT', 0, 1, u'银行名称'],
            [' HEAD',   'SYS_DATE',  ' C', 8,  0, ' ',    ' LERT', 0, 1, u'打印日期'],
            [' HEAD',   'USER_ID',   ' C', 20, 0, ' ',    ' LERT', 0, 1, u'打印用户'],
            [' HEAD',   '<RptNm>',   ' C', 0,  0, ' ',    ' LERT', 0, 1, u'**在这儿填写此报表名**'],
            [' HEAD',   'SYS_TIME',  ' C', 8,  0, ' MSW', ' LERT', 0, 1, u'时间: '],
            [' HEAD',   'PROC_DATE', ' C', 8,  0, ' MSW', ' LERT', 0, 1, u'处理日: '],
            ]

    #--------------------------------------------------
    # required methods for the wxPyGridTableBase interface

    def GetNumberRows(self):
        return len(self.data) + 1

    def GetNumberCols(self):
        return len(self.data[0])

    def IsEmptyCell(self, row, col):
        try:
            return not self.data[row][col]
        except IndexError:
            return True

    def GetValue(self, row, col):
        try:
            #print "%d|%d --%s" % (row, col, self.data[row][col])
            return self.data[row][col]
        except IndexError:
            return ''

    def SetValue(self, row, col, value):
        def innerSetValue(row, col, value):
            try:
                self.data[row][col] = value
            except IndexError:
                self.data.append([''] * self.GetNumberCols())
                #innerSetValue(row, col, value)

                msg = gridlib.GridTableMessage(self,
                        gridlib.GRIDTABLE_NOTIFY_ROWS_APPENDED,1)
                self.GetView().ProcessTableMessage(msg)
        innerSetValue(row, col, value)

    #--------------------------------------------------
    # Some optional methods

    def GetColLabelValue(self, col):
        return self.colLabels[col]

    def GetTypeName(self, row, col):
        return self.dataTypes[col]

    # Called to determine how the data can be fetched and stored by the
    # editor and renderer.
    def CanGetValueAs(self, row, col, typeName):
        colType = self.dataTypes[col].split(':')[0]
        if typeName == colType:
            return True
        else:
            return False

    def CanSetValueAs(self, row, col, typeName):
        return self.CanGetValueAs(row, col, typeName)

    def Clear(self):
        self.data = []

#---------------------------------------------------------------------------

class CustTableGrid(gridlib.Grid):
    def __init__(self, parent, log):
        gridlib.Grid.__init__(self, parent, -1)

        self.table = CustomDataTable(log)

        # The second parameter means that the grid is to take ownership of the
        # table and will destroy it when done.  Otherwise you would need to keep
        # a reference to it and call it's Destroy method later.
        self.SetTable(self.table, True)

        #self.SetRowLabelSize(0)
        self.SetMargins(0,0)
        self.AutoSizeRows(True)
        self.AutoSizeColumns(True)
        #self.AutoSize()

        #gridlib.EVT_GRID_CELL_LEFT_CLICK(self.OnCellLeftClick)
        #self.Bind(gridlib.EVT_GRID_CELL_LEFT_DCLICK, self.OnLeftDClick)

        self.Bind(gridlib.EVT_GRID_CELL_CHANGE, self.OnCellChange)
        self.Bind(gridlib.EVT_GRID_SELECT_CELL, self.OnSelectCell)

    # I do this because I don't like the default behaviour of not starting the
    # cell editor on double clicks, but only a second click.
    def OnLeftDClick(self, evt):
        if self.CanEnableCellControl():
            self.EnableCellEditControl()

    def OnSelectCell(self, evt):
        #print "%s : %d-%d" % (msg, evt.GetRow(), evt.GetCol())
        row = self.GetGridCursorRow()
        col = self.GetGridCursorCol()
        value = self.GetCellValue(row, col)
        print "OnSelectCell: Value = %s" % value
        #wx.MessageBox("Are you sure?","Checking", wx.YES_NO)
        evt.Skip()

    def OnCellChange(self, evt):
        print "OnCellChange"
        row = self.GetGridCursorRow()
        col = self.GetGridCursorCol()
        value = self.GetCellValue(row, col)
        self.table.SetValue(row, col, value)

        evt.Skip()

#---------------------------------------------------------------------------

class TestFrame(wx.Frame):
    def __init__(self, parent, log):
        wx.Frame.__init__(self, parent, -1, "Edit Report Data", size=(800,600))

        p = wx.Panel(self, -1, style=0)
        self.grid = CustTableGrid(p, log)
        b = wx.Button(p, -1, "CreateXml")
        b.SetDefault()
        self.Bind(wx.EVT_BUTTON, self.OnButton, b)
        #b.Bind(wx.EVT_SET_FOCUS, self.OnButtonFocus)
        bs = wx.BoxSizer(wx.VERTICAL)
        bs.Add(self.grid, 1, wx.GROW|wx.ALL, 5)
        bs.Add(b)
        p.SetSizer(bs)

    def OnButton(self, evt):
        print "button OnButton"
        self.grid.ClearGrid()

    def OnButtonFocus(self, evt):
        print "button focus"
        self.grid.ClearGrid()


#---------------------------------------------------------------------------

if __name__ == '__main__':
    import sys,os
    app = wx.PySimpleApp()
    #print "%d ============" % os.getpid()
    TestFrame(None, sys.stdout).Show(True)
    app.MainLoop()


#---------------------------------------------------------------------------
